package com.mall.business.controller;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.business.domain.*;
import com.mall.business.service.*;
import com.mall.common.annotation.RepeatSubmit;
import com.mall.common.core.controller.BaseController;
import com.mall.common.core.domain.AjaxResult;
import com.mall.common.core.domain.entity.QrRzDTO;
import com.mall.common.core.domain.entity.SysUser;
import com.mall.common.core.page.TableDataInfo;
import com.mall.common.utils.DateUtils;
import com.mall.common.utils.SecurityUtils;
import com.mall.common.utils.StringUtils;
import com.mall.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static io.lettuce.core.pubsub.PubSubOutput.Type.message;

/**
 * 我的接口
 */
@RestController
@RequestMapping("/webApiMy")
public class ApiMyController extends BaseController {

    @Autowired
    private ITWalletService tWalletService;

    @Autowired
    private ITCouponUserService tCouponUserService;


    @Autowired
    private ITTxSqService tTxSqService;


    @Autowired
    private ITWalletService walletService;

    @Autowired
    private ITConfigService tConfigService;

    @Autowired
    private ITSocreService socreService;
    @Autowired
    private ITMemberLevelService memberLevelService;


    @Autowired
    private ITOrderPjService tOrderPjService;

    @Autowired
    private ITOrderService orderService;




    @Autowired
    private ITProblemService problemService;


    @Autowired
    private ISysUserService sysUserService;


    @Autowired
    private ITUserSignService tUserSignService;


    @Autowired
    private ITUserAddressService tUserAddressService;


    /**
     * 我的地址
     */
    @GetMapping("/getMyAddressList")
    public AjaxResult getMyAddressList() {
        String userId = SecurityUtils.getUserIdStr();
        TUserAddress userAddress = new TUserAddress();
        userAddress.setUserId(userId);
        List<TUserAddress> tUserAddresses = tUserAddressService.selectTUserAddressList(userAddress);
        return AjaxResult.success(tUserAddresses);
    }


    /**
     * 保存地址
     */
    @RepeatSubmit
    @PostMapping("saveUpdateUserAddress")
    @Transactional
    public AjaxResult saveUpdateUserAddress(@Validated @RequestBody TUserAddress address) {
        if (StringUtils.isEmpty(address.getId())) {
            if ("1".equals(address.getIsMr())) {
                // 默认 将之前的默认 地址取消
                tUserAddressService.cancleUserOtherMrAddress();
            }
            address.setUserId(SecurityUtils.getUserIdStr());
            tUserAddressService.save(address);
        } else {
            if ("1".equals(address.getIsMr())) {
                // 默认 将之前的默认 地址取消
                tUserAddressService.cancleUserOtherMrAddress();
            }
            address.setUserId(SecurityUtils.getUserIdStr());
            tUserAddressService.updateById(address);
        }

        return AjaxResult.success();
    }


    /**
     * 删除地址
     */
    @PostMapping("deleteUserAddress")
    public AjaxResult deleteUserAddress(@RequestBody TUserAddress address) {
        if (StringUtils.isEmpty(address.getId())) {
            return AjaxResult.error("获得参数失败");
        }
        tUserAddressService.removeById(address.getId());
        return AjaxResult.success();
    }


    /**
     * 个人详细信息
     */
    @GetMapping("/getMyIfnfo")
    public AjaxResult getMyIfnfo() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        BigDecimal totalMoney = orderService.getOrderPayMoney(SecurityUtils.getUserIdStr());
        // 获取用户等级
        TMemberLevel userMemberLevel = memberLevelService.getUserMemberLevel(totalMoney);
        System.out.println(totalMoney);
        if(userMemberLevel !=null){
            sysUser.setLevel(userMemberLevel.getLevel()+"");
        }
        return AjaxResult.success(sysUser);
    }

    /**
     * 企业认证
     */
    @PostMapping("/updateQyRz")
    public AjaxResult updateQyRz(@RequestBody QrRzDTO vo) {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        String checkStatus = sysUser.getCheckStatus();
        if ("2".equals(checkStatus)) {
            throw new RuntimeException("您已经通过企业认证");
        }
        SysUser rezuser = new SysUser();
        rezuser.setJgType(vo.getJgType());
        rezuser.setXkzImage(vo.getXkzImage());
        rezuser.setWtsImage(vo.getWtsImage());
        rezuser.setYyzzImage(vo.getYyzzImage());
        rezuser.setCgSfzImage(vo.getCgSfzImage());
        rezuser.setCgSfzfmImage(vo.getCgSfzfmImage());
        rezuser.setSydwzsImage(vo.getSydwzsImage());
        rezuser.setWtrSfzImage(vo.getWtrSfzImage());
        rezuser.setWtrSfzfmImage(vo.getWtrSfzfmImage());
        rezuser.setCheckStatus("1");
        rezuser.setUserId(userId);
        rezuser.setNickName(vo.getNickName());
        sysUserService.updateUserApp(rezuser);
        return AjaxResult.success();
    }

    /**
     * 我的余额（总金额）
     */
    @GetMapping("/getMyTotalMoney")
    public AjaxResult getMyTotalMoney() {
        BigDecimal totalMoney = tWalletService.getTotalMoney();
        return AjaxResult.success(totalMoney);
    }

    /**
     * 我的余额明细(分页)
     */
    @GetMapping("/getTWalletList")
    public TableDataInfo getTWalletList(TWallet vo) {
        startPage();
        vo.setUserId(SecurityUtils.getUserIdStr());
        List<TWallet> tWallets = tWalletService.selectTWalletList(vo);
        return getDataTable(tWallets);
    }


    /**
     * 我的优惠券明细(分页)
     */
    @GetMapping("/getMyCouponList")
    public TableDataInfo getCouponList(TCouponUser vo) {
        startPage();
        vo.setUserId(SecurityUtils.getUserIdStr());
        List<TCouponUser> tCouponUsers = tCouponUserService.selectTCouponUserList(vo);
        return getDataTable(tCouponUsers);
    }


    /**
     * 提现申请
     */
    @PostMapping("/updateTxSq")
    @RepeatSubmit
    public AjaxResult updateTxSq(@Validated TTxSq vo) {
        BigDecimal txmoney = vo.getMoney();
        if (txmoney.compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("提现金额必须大于0");
        }
        //用户
        // 余额
        BigDecimal totalMoney = walletService.getTotalMoney();
        if (txmoney.compareTo(totalMoney) > 0) {
            throw new RuntimeException("提现金额大于用户余额");
        }
        // 最定提现金额
        String zdtx_money = tConfigService.getConfigValue("zdtx_money");
        if (zdtx_money != null) {
            if (txmoney.compareTo(new BigDecimal(zdtx_money)) < 0) {
                throw new RuntimeException("提现金额小于最低提现金额");
            }
        }
        vo.setUserId(SecurityUtils.getUserIdStr());
        vo.setCheckStatus("1");
        tTxSqService.save(vo);
        return AjaxResult.success();
    }


    /**
     * 我的积分（总余额）
     */
    @GetMapping("/getMyTotalScore")
    public AjaxResult getMyTotalScore() {
        BigDecimal totalScore = socreService.getTotalScore();
        return AjaxResult.success(totalScore);
    }


    /**
     * 我的积分明细(分页)
     */
    @GetMapping("/getScoreList")
    public TableDataInfo getScoreList(TSocre vo) {
        startPage();
        vo.setUserId(SecurityUtils.getUserIdStr());
        List<TSocre> tSocres = socreService.selectTSocreList(vo);
        return getDataTable(tSocres);
    }


    /**
     * 会员等级列表
     */
    @GetMapping("/getMemberLevelList")
    public AjaxResult getMemberLevelList(TMemberLevel vo) {
        List<TMemberLevel> tMemberLevels = memberLevelService.selectTMemberLevelList(vo);
        return AjaxResult.success(tMemberLevels);
    }


    /**
     * 问题反馈
     */
    @RepeatSubmit
    @PostMapping("/saveProblem")
    public AjaxResult saveProblem(@Validated  @RequestBody TProblem vo) {
        vo.setUserId(SecurityUtils.getUserIdStr());
        problemService.save(vo);
        return AjaxResult.success();
    }


    /**
     * 保存用户签到
     */
    @RepeatSubmit
    @PostMapping("/addUserSign")
    @Transactional
    public AjaxResult addUserSign() {
        QueryWrapper<TUserSign> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", SecurityUtils.getUserId());
        queryWrapper.apply("date_format(sign_date,'%Y-%m-%d') = date_format(NOW(),'%Y-%m-%d')");
        Long count = tUserSignService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error("已经签到过");
        }
        TUserSign userSign = new TUserSign();
        // 签到用户
        userSign.setUserId(SecurityUtils.getUserIdStr());
        // 签到时间
        userSign.setSignDate(DateUtils.getNowDate());
        tUserSignService.save(userSign);
        // 签到送积分
        String sign_score = tConfigService.getConfigValue("sign_score");
        if (!StringUtils.isEmpty(sign_score)) {
            TSocre tsocre = new TSocre();
            tsocre.setScore(new BigDecimal(sign_score));
            tsocre.setUserId(SecurityUtils.getUserIdStr());
            tsocre.setSrType("3");
            tsocre.setRemark("打卡送积分");
            socreService.save(tsocre);
        }
        return AjaxResult.success();
    }

    /**
     * 用户签到数据
     */
    @GetMapping("my/getUserSignMonth")
    public AjaxResult getUserSignMonth() {

        AjaxResult ajaxResult = AjaxResult.success();

        // 获取今天是否已经签到了

        QueryWrapper<TUserSign> query = new QueryWrapper<>();
        query.eq("user_id", SecurityUtils.getUserId());
        query.apply("date_format(sign_date,'%Y-%m-%d') = date_format(NOW(),'%Y-%m-%d')");
        Long count = tUserSignService.count(query);
        ajaxResult.put("isNowSign", count);


        QueryWrapper<TUserSign> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", SecurityUtils.getUserId());
        queryWrapper.apply("date_format(sign_date,'%Y-%m') = date_format(NOW(),'%Y-%m')");
        List<TUserSign> list = tUserSignService.list(queryWrapper);
         Integer  monthsign_num = 0;
        //获取连续签到的天数
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, List<TUserSign>> hashmapstr = list.stream().collect(Collectors.groupingBy(e -> DateUtils.parseDateToStr("dd", e.getSignDate())));
            Map<String, List<TUserSign>> newHashmapstr = new HashMap<>();
            for (Map.Entry<String, List<TUserSign>> stringListEntry : hashmapstr.entrySet()) {
                String s = removeLeadingZeroIfLessThanTen(stringListEntry.getKey());
                newHashmapstr.put(s, stringListEntry.getValue());
                monthsign_num++;
            }
             ajaxResult.put("data", newHashmapstr);
            ajaxResult.put("monthsignNum", monthsign_num);
            return ajaxResult;
        } else {
            return ajaxResult;
        }


    }

    public String removeLeadingZeroIfLessThanTen(String numberStr) {
        if (numberStr != null && numberStr.length() == 2 && numberStr.charAt(0) == '0' && Character.isDigit(numberStr.charAt(1))) {
            return numberStr.substring(1);
        }
        return numberStr;
    }


}
